
'use strict';

/*-------------------------------------------------------------
       _                         
 _   _(_) __ _ _ __ _____      __
| | | | |/ _` | '__/ _ \ \ /\ / /
| |_| | | (_| | | | (_) \ V  V / 
\__ , |_|\__, |_|  \___/ \_/\_/  
 |___/   |___/ (C)2023 shhoo.cn

 1、添加WS100数据解析SensorDataParser
 2、添加
-------------------------------------------------------------*/
import moment from 'moment';
moment.locale('zh-cn');
import { RedisGatewayClass } from "../lib/redis_gateway";
import Mysql from "../lib/mysqlUtil";
import { SendLedParams } from "./led"
const Redis = require('ioredis');
const localSetRedisCli = new Redis(6379, "127.0.0.1");
import { covertBCDStringToFloatNumber, nanNumber2Null, generateCRC8Code, convertHexNumStrToWantedLengthUppercase } from "../lib/basic"
var counterAverageWind: Array<number>;//风速采集数据
const windPositionParser = ["北", "东北", "东", "东南", "南", "西南", "西", "西北", "无"];
/*------------发送指令参数-------------*/
const db_loRa_Outside_9Factor_Type_A = "deviceSn varchar(18),snsorTypId varchar(4),dataTyp varchar(64),vol int,temp float,humi float,illu float,airprs float,windSpeed float,windPosition varchar(64),uv float,CO2 float,TVOCs float,isRain int(1),t bigint,primary key(t),INDEX index_t (t)";
var lastTime = 0;
/**
 * 十一因素传感器报警阈值设置
 * @param {*} sensor_alias 
 * @param {*} f_sensor_sn 
 * @param {*} sensor_data 
 */
function __generat9OutsideFacAlarmContent(sensor_alias, f_sensor_sn, sensor_data) {
    let alarmContent = '';
    let enableAlarm = 0;
    Mysql.QueryConditionalDataFromTable('t_alarm', `f_device_sn='${f_sensor_sn}'`).then((alramData) => {
        if (alramData.length > 0) {
            console.log(alramData[0]);
            try {
                //console.log("<<<<<<<<<<<<<<<<<<<<<<<<<<<",sensor_data);
                let f_alarm_settings = JSON.parse(alramData[0].f_alarm_settings);
                enableAlarm = alramData[0].f_enable;
                let user_params = JSON.parse(alramData[0].f_user_params);
                console.log(f_alarm_settings.vol, enableAlarm, user_params);
                //{"vol":[1,null,null],"temp":[1,10.1,40],"humi":[1,30.5,95.5],"illu":[0,null,null],"airprs":[0,null,null],"uv":[0,null,null],"CO2":[0,null,null],"TVOCs":[0,null,null],"soilTemp":[0,null,null],"soilHum":[0,null,null],"soilEC":[0,null,null],"soilSalt":[0,null,null]}
                if (enableAlarm === 1) {
                    let volLimit = f_alarm_settings.vol;
                    if (volLimit[0] === 1) {
                        if (parseInt(sensor_data.vol) < volLimit[1] && volLimit[1] != null && parseInt(sensor_data.vol) < volLimit[2]) {
                            alarmContent += `\n电压低阈值:${parseInt(sensor_data.vol)}mv ↓，[阈值<${volLimit[1]}mv]`;
                            console.log("VOL阈值下限------------------------------------")
                        } else if (parseInt(sensor_data.vol) > volLimit[1] && parseInt(sensor_data.vol) > volLimit[2] && volLimit[2] != null) {
                            alarmContent += `\n电压超阈值:${parseInt(sensor_data.vol)}mv ↑，[阈值>${volLimit[2]}mv]`;
                            console.log("VOL阈值上限------------------------------------", sensor_data.vol, volLimit[1], volLimit[2]);
                        }
                    }
                    let tempLimit = f_alarm_settings.temp;
                    if (tempLimit[0] === 1) {
                        console.log("enable alarm", sensor_data.temp, tempLimit[1], tempLimit[2]);
                        if (parseInt(sensor_data.temp) < tempLimit[1] && tempLimit[1] != null && parseInt(sensor_data.temp) < tempLimit[2]) {
                            alarmContent += `\n温度低阈值:${parseInt(sensor_data.temp)}℃ ↓，[阈值<${tempLimit[1]}℃]`;
                            console.log("TEMP阈值下限------------------------------------")
                        } else if (parseInt(sensor_data.temp) > tempLimit[1] && parseInt(sensor_data.temp) > tempLimit[2] && tempLimit[2] != null) {
                            alarmContent += `\n温度超阈值:${parseInt(sensor_data.temp)}℃ ↑，[阈值>${tempLimit[2]}℃]`;
                            console.log("TEMP阈值上限------------------------------------", sensor_data.temp, tempLimit[1], tempLimit[2]);
                        }
                    }
                    let humLimit = f_alarm_settings.humi;
                    //console.log(">>>>>>>>>>>>>>>>>>>>>>",sensor_data.humi,humLimit);
                    if (humLimit[0] === 1) {
                        if (sensor_data.humi < humLimit[1] && humLimit[1] != null && sensor_data.humi < humLimit[2]) {
                            alarmContent += `\n湿度低阈值:${sensor_data.humi}% ↓，[阈值<${humLimit[1]}%]`;
                            console.log("HUM阈值下限------------------------------------", sensor_data.humi, humLimit[1])
                        } else if (sensor_data.humi > humLimit[1] && sensor_data.humi > humLimit[2] && humLimit[2] != null) {
                            alarmContent += `\n湿度超阈值:${sensor_data.humi}% ↑，[阈值>${humLimit[2]}%]`;
                            console.log("HUM阈值上限------------------------------------", sensor_data.humi, humLimit[1], humLimit[2])
                        }
                    }
                    let illuLimit = f_alarm_settings.illu;
                    if (illuLimit[0] === 1) {
                        if (sensor_data.illu < illuLimit[1] && illuLimit[2] != null && sensor_data.illu < illuLimit[2]) {
                            alarmContent += `\n光照度低阈值:${sensor_data.illu}lux ↓，[阈值<${illuLimit[1]}lux]`;
                        } else if (sensor_data.illu > illuLimit[1] && sensor_data.illu > illuLimit[2] && illuLimit[2] != null) {
                            alarmContent += `\n光照度超阈值:${sensor_data.illu}lux ↑，[阈值>${illuLimit[2]}lux]`;
                        }
                    }
                    let airprsLimit = f_alarm_settings.airprs;
                    if (airprsLimit[0] === 1) {
                        if (sensor_data.airprs < airprsLimit[1] && sensor_data.airprs < airprsLimit[2]) {
                            alarmContent += `\n大气压低阈值:${sensor_data.airprs}kPa ↓，[阈值<${airprsLimit[1]}kPa]`;
                        } else if (sensor_data.airprs > airprsLimit[1] && sensor_data.airprs > airprsLimit[2]) {
                            alarmContent += `\n大气压超阈值:${sensor_data.airprs}kPa ↑，[阈值>${airprsLimit[2]}kPa]`;
                        }
                    }
                    let uvLimit = f_alarm_settings.uv;
                    let CO2Limit = f_alarm_settings.CO2;
                    let TVOCsLimit = f_alarm_settings.TVOCs;

                    if (alarmContent !== '') {
                        console.log("user_params--------------------------->>>>>>", user_params);
                        user_params.forEach((userParams) => {
                            console.log(JSON.stringify(userParams));
                            //Warning.sendWxAlarmMsgNeedRequestUserParams(sensor_alias, '采集数据超阈值', moment(sensor_data.t).format('YYYY MM-DD HH:mm:ss'), alarmContent, `https://yigrow.cn`, `${JSON.stringify(userParams)}`);
                            // Warn.sendDeviceWarning(true, null,
                            //     "尊敬的用户，您的设备发生如下报警：",
                            //     `【${baseName}/${sensor_alias}】`,
                            //     `${moment().format('YYYY-MM-DD HH:mm:ss')}`,
                            //     '采集数据超阈值',
                            //     alarmContent, "",
                            //     "https://yigrow.cn")
                        })
                    }
                }
            } catch (error) {

            }
        }
    })
}
/** 设置传感器时间间隔及RTC时间(A011)
* 
* @param { string } sendAddr 发送地址
* @param { string } deviceTypeId 设备类型Id
* @param { string } zoneId 区域Id
* @param { string } channel 路数
*/
function setIntervalAndRtc(RedisGateway: RedisGatewayClass, sendAddr, deviceTypeId, zoneId, channel, interval, isBroadcast) {
    //                   0  1-2  3  4-5  6  7  8  9  10-11 12-18          19-26
    //61 00000071 000100 FE A011 17 C001 55 01 55 55 003C  20190322170147 0000000000000000 CB 0D0A0D0A0D0A
    //61 00000071 000100 FE A011 17 5555 55 01 55 55 003C  20190322182303 0000000000000000 DB 0D0A0D0A0D0A
    try {
        console.log('loRa Set Interval And Rtc!!!!')
        let deviceHead = Buffer.from([0x61]);
        let deviceOthers = Buffer.from([0x00, 0x01, 0x00]);
        let newTime = Buffer.from(moment().format('YYYYMMDDHHmmss'), 'hex');
        let frameId = Buffer.from([0xA0, 0x11]);
        let interVal = convertHexNumStrToWantedLengthUppercase(parseInt(interval, 10).toString(16), 4);
        console.log(interVal);
        let allocate = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
        let addr = sendAddr;
        let broadCast = '55';
        if (isBroadcast !== true) {
            broadCast = '00';
        }
        if (zoneId === 'NAN') {
            zoneId = '55';
        }
        //console.log(addr, broadCast);
        let ackFrameBuf = Buffer.concat([Buffer.from([0xfe]), frameId, Buffer.from([0x00]), Buffer.from(deviceTypeId, 'hex'), Buffer.from(broadCast, 'hex'), Buffer.from(zoneId, 'hex'), Buffer.from([0x00]), Buffer.from(channel, 'hex'), Buffer.from(interVal, 'hex'), newTime, allocate, Buffer.from([0x00, 0xd, 0xa, 0xd, 0xa, 0xd, 0xa])]);
        let dataLenth = ackFrameBuf.length - 11;
        ackFrameBuf[3] = dataLenth;
        //console.log('dataLenth', ackFrameBuf[3].toString(16).toUpperCase());
        let crc8Buf = ackFrameBuf.slice(4, -7);
        //console.log('crc8Buf', crc8Buf.toString('hex').toUpperCase());
        ackFrameBuf[ackFrameBuf.length - 7] = generateCRC8Code(crc8Buf);
        let sendCmd = Buffer.alloc(ackFrameBuf.length + 3);
        sendCmd = Buffer.concat([deviceHead, Buffer.from(addr, 'hex'), deviceOthers, ackFrameBuf]);
        console.log('sendcmd', sendCmd.toString('hex').toUpperCase());
        RedisGateway.PubSerialDirectCmd(sendCmd.toString('hex').toUpperCase(), 1);

    } catch (error) {
        console.log(`[]: ${error.toString()}`);
    }
}
//?移除最大最小值
function spliceMaxMin(arry: Array<number>) {
    var result = arry.splice(0),
        max = Math.max(...result),
        min = Math.min(...result)
    for (var i = 0; i < result.length; i++) {
        if (result[i] == max) {
            result.splice(i, 1)
        }
        if (result[i] == min) {
            result.splice(i, 1)
        }
    }
    return result
}
function __retrieveData(array: Array<number>, value: number) {
    let arr = array.concat([]);
    arr.push(value);
    arr.sort((a, b) => { return b - a });
    let index = arr.indexOf(value);
    if (index === 0) {
        return arr[index + 1];
    } else if (index === array.length - 1) {
        return arr[index - 1];
    }
    let resultIndex = arr[index] - arr[index - 1] > arr[index + 1] - arr[index] ? index + 1 : index - 1;
    return arr[resultIndex];
}
function SensorDataParser(RedisGateway: RedisGatewayClass, addr: string, sensorData: Buffer) {
    try {
        console.log(addr,sensorData.toString('hex').toUpperCase())
        let SensorType = sensorData.slice(4, 6).toString('hex');
        let BatVol = 24000;//parseInt(sensorData.slice(6, 8).toString('hex'), 16);
        let Temperature = covertBCDStringToFloatNumber(sensorData.slice(8, 10).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(10, 11).toString('hex'), 2));
        let Humidity = covertBCDStringToFloatNumber(sensorData.slice(11, 13).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(13, 14).toString('hex'), 2));
        let LumiIntensity = covertBCDStringToFloatNumber(sensorData.slice(14, 18).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(18, 19).toString('hex'), 2));
        let AirPressure = null;
        let windSpeed = covertBCDStringToFloatNumber(sensorData.slice(19, 21).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(21, 22).toString('hex'), 2));
        let windPosition = parseInt(sensorData.slice(22, 24).toString('hex'), 16) > 7 ? 8 : parseInt(sensorData.slice(22, 24).toString('hex'), 16);
        let UvIntensity = covertBCDStringToFloatNumber(sensorData.slice(24, 26).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(26, 27).toString('hex'), 2));
        let CO2 = covertBCDStringToFloatNumber(sensorData.slice(27, 29).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(29, 30).toString('hex'), 2));
        let TVOCs = covertBCDStringToFloatNumber(sensorData.slice(30, 32).toString('hex'), convertHexNumStrToWantedLengthUppercase(sensorData.slice(32, 33).toString('hex'), 2));
        let isRain = parseInt(sensorData.slice(33, 34).toString('hex'), 16);
        if (isRain == 1 || isRain == 0) {
            localSetRedisCli.set(`CurrentIsRain`, isRain.toString());
            SendLedParams(1, windSpeed.toFixed(1), false);
            SendLedParams(2, nanNumber2Null(windPosition) == null ? "" : windPositionParser[windPosition], true);
            SendLedParams(3, LumiIntensity.toFixed(0), false);
            SendLedParams(4, Temperature.toFixed(1), false);
            SendLedParams(5, Humidity.toFixed(1), false);
            SendLedParams(6, isRain == 1 ? "是" : "否", true);
            //console.log("Time:" + sensorData.slice(34, 40).toString('hex'));
            let year = parseInt(sensorData.slice(33, 35).toString('hex'));
            let month = parseInt(sensorData.slice(35, 36).toString('hex')) - 1;
            let day = parseInt(sensorData.slice(36, 37).toString('hex'));
            let hours = parseInt(sensorData.slice(37, 38).toString('hex'))
            let minutes = parseInt(sensorData.slice(38, 39).toString('hex'));
            let seconds = parseInt(sensorData.slice(39, 40).toString('hex'));
            let timeObj = new Date(year, month, day, hours, minutes, seconds);
            //使用传感器时间
            //let timeStamp = timeObj.getTime(); 
            //使用网关电脑当前时间
            let timeStamp = moment().unix() * 1000;
            if (Humidity == 0) {
                Humidity = 100;
            }
            // console.log(lastTime, timeStamp,(lastTime + 30 * 1000))
            if (timeStamp >= (lastTime + 30 * 1000)) {
                lastTime = timeStamp;
                //console.log(moment().format('YYYY MM-DD HH:mm:ss\n') + `Addr:${addr}`);
                console.log("timeStamp: SensorRtc:" + timeObj.getTime() + "(" + sensorData.slice(45, 52).toString('hex') + ")" + "   SystemCurrentTime:" + timeStamp.toString() + " (" + moment().format('YYYYMMDDHHmmss') + ")");
                console.log("Addr:" + addr + ' SensorType:' + SensorType + " BatVol:" + BatVol + " Temperature:" + Temperature + " Humidity:" + Humidity + " LumiIntensity:" + LumiIntensity + " AirPressure:" + AirPressure + "  windSpeed:" + windSpeed + "  windPosition:" + windPosition + " UvIntensity:" + UvIntensity + " CO2:" + CO2 + " TVOCs:" + TVOCs + " isRain:" + isRain);
                Mysql.QueryNeededParamsFromTable("t_sensor", 'f_sensor_addr', `'${addr}'`).then((data) => {
                    if (Array.isArray(data) && data.length > 0) {
                        let sensor_sn = data[0].f_sensor_sn;
                        let sensor_alias = data[0].f_sensor_alias;
                        let sensor_data = {
                            "vol": BatVol,
                            "temp": Temperature,
                            "humi": Humidity,
                            "illu": LumiIntensity,
                            "airprs": AirPressure,
                            "windSpeed": windSpeed,
                            "windPosition": nanNumber2Null(windPosition) == null ? null : windPositionParser[windPosition],
                            "uv": UvIntensity,
                            "CO2": CO2,
                            "TVOCs": TVOCs,
                            "isRain": isRain,
                            "t": timeStamp
                        }
                        let sendData = {
                            "f_sensor_sn": sensor_sn,
                            "sensorTypeId": '0003',
                            "data": sensor_data
                        }
                        console.log("\n------------------配置下雨关棚参数-----------------")
                        RedisGateway.PubEnvControlPara(sensor_sn, "LoRa_Outside_9Factor_Type_A", sensor_data)
                        __generat9OutsideFacAlarmContent(sensor_alias, sensor_sn, sensor_data);
                        Mysql.UpdateParamsIntoTable("t_sensor", 'f_sensor_sn', `'${sensor_sn}'`, `f_sensor_status='查询数据成功',f_last_value='${JSON.stringify(sensor_data)}',f_sensor_edit_time='${moment().format('YYYY-MM-DD HH:mm:ss')}'`).then((updateSta) => {
                            console.log('[t_sensor--UPDATE] UPDATE db_sensor sensor Status successfully!!!');
                            RedisGateway.PubSysCmdAck('SENSOR', 'UPDATE', `00000000000${moment().unix().toString()}`, 'succcess', '插入数据成功', sensor_data);
                        }).catch((err) => {
                            console.log(err)
                        })
                        Mysql.QueryConditionalDataFromTable("t_sensor", `f_sensor_addr='${addr}'`).then((data) => {
                            if (data.length > 0) {
                                let interVal = parseInt(data[0].f_sensor_interval);
                                //	console.log(interVal);
                                setIntervalAndRtc(RedisGateway, addr, '0003', '55', '00', interVal, true);
                            }
                        }).catch((err) => {
                            console.log(err)
                        })
                        ///Step1 上报实时数据
                        //	console.log('LoRa Wireless Outside 9Fac Wther Soil A Sensor Data:--->' + JSON.stringify(sendData));
                        RedisGateway.PubSensorData('SENSOR_DATA', 'QUERY', `00000000000${moment().unix().toString()}`, 'success', '实时数据采集成功', sendData);
                        ///Step2 存储历史数据
                        //表名构成：t + '_' + SN号 + '' + 'data' + '_' + 年 如：t_122100d0ccdd_data_2018
                        let currentYear = moment().format('YYYY');
                        let tableName = `t_${data[0].f_sensor_sn}_data_${currentYear}`;
                        Mysql.TableIsExists(tableName).then((sta) => {
                            if (sta === true) {
                                console.log("table is exists!!");
                                let paramKeys = "deviceSn,snsorTypId,dataTyp,vol,temp,humi,illu,airprs,windSpeed,windPosition,uv,CO2,TVOCs,isRain,t";
                                let paramDatas = `'${data[0].f_sensor_sn}','0003','LoRa_Outside_9Factor_Type_A',${nanNumber2Null(BatVol)},${nanNumber2Null(Temperature)},${nanNumber2Null(Humidity)},${nanNumber2Null(LumiIntensity)},${null},${nanNumber2Null(windSpeed)},'${windPositionParser[windPosition]}',${nanNumber2Null(UvIntensity)},${nanNumber2Null(CO2)},${nanNumber2Null(TVOCs)},${nanNumber2Null(isRain)},${timeStamp}`;
                                Mysql.InsertParamsIntoTable(tableName, paramKeys, paramDatas).then((sta) => {
                                    console.log("Insert new datas is successfully!!");
                                }).catch((err) => {
                                    console.log(err)
                                })
                            } else {
                                //console.log("table does not exists!!");
                                Mysql.CreateTable(tableName, db_loRa_Outside_9Factor_Type_A).then((sta) => {
                                    console.log(`\nCREATE TABLE ${tableName} is successfully!!!!`);
                                    let paramKeys = "deviceSn,snsorTypId,dataTyp,vol,temp,humi,illu,airprs,windSpeed,windPosition,uv,CO2,TVOCs,isRain,t";
                                    let paramDatas = `'${data[0].f_sensor_sn}','0003','LoRa_Outside_9Factor_Type_A',${nanNumber2Null(BatVol)},${nanNumber2Null(Temperature)},${nanNumber2Null(Humidity)},${nanNumber2Null(LumiIntensity)},${null},${nanNumber2Null(windSpeed)},'${windPositionParser[windPosition]}',${nanNumber2Null(UvIntensity)},${nanNumber2Null(CO2)},${nanNumber2Null(TVOCs)},${nanNumber2Null(isRain)},${timeStamp}`;
                                    Mysql.InsertParamsIntoTable(tableName, paramKeys, paramDatas).then((sta) => {
                                        if (sta === true) {
                                            console.log("Insert new datas is successfully!!");
                                        }
                                    }).catch((err) => {
                                        console.log(err)
                                    })
                                }).catch((err) => {
                                    console.log(err)
                                })
                            }
                            console.log('配置风速控制')
                            console.log(`当前风速为:${windSpeed}`)
                            console.log(sensor_sn)
                            Mysql.QueryNeededParamsLimitFromTable(tableName, `deviceSn`, `'${sensor_sn}'`, 9).then((msg) => {
                                console.log(msg)
                                if (Array.isArray(msg)) {
                                    msg.forEach(sensorInfo => {
                                        counterAverageWind.push(parseInt(sensorInfo.windSpeed))
                                    })
                                    Mysql.QueryAllParamsFromTable("t_auto_wind").then((env) => {
                                        try {
                                            if (Array.isArray(env)) {
                                                let averageWind = 0;
                                                if (typeof (windSpeed) === "number" && isNaN(windSpeed) == false) {
                                                    counterAverageWind.push(windSpeed)
                                                }
                                                console.log(`采集的全部风速值:${counterAverageWind}`)
                                                let spliceMaxMinArray = spliceMaxMin(counterAverageWind)//!去除最大最小值后数组
                                                console.log(`去除最大最小值后的数组:${spliceMaxMinArray}`)
                                                //!计算平均值
                                                var average = AverageWind => AverageWind.reduce((acc, val) => acc + val, 0) / spliceMaxMinArray.length;
                                                averageWind = Math.round(average(spliceMaxMinArray))
                                                console.log(`平均风速=====${averageWind}`)

                                                for (let i = 0; i < env.length; i++) {
                                                    let speedArray = JSON.parse(env[i].windSpeedArray)//设定风速
                                                    let wardOpenArray = JSON.parse(env[i].wardOpenLimitArray)//迎风面开度
                                                    let leeOpenArray = JSON.parse(env[i].leeOpenLimitArray)//背风面开度
                                                    let maxSpeen = Math.max(...speedArray)//最大风速

                                                    if (speedArray.length > 0) {
                                                        console.log(`数据库中最大风速:${maxSpeen}`)
                                                        if (averageWind > maxSpeen) {
                                                            console.log('风速计算后超过最大风速了')
                                                            let wardOpenLimit = wardOpenArray[wardOpenArray.length - 1];
                                                            let leeOpenLimit = leeOpenArray[leeOpenArray.length - 1];
                                                            let windOpenSql = `windwardOpen=${wardOpenLimit},leewardOpen=${leeOpenLimit}`
                                                            Mysql.UpdateParamsIntoTable('t_auto_wind', `zoneId`, env[i].zoneId, windOpenSql).then((status) => {
                                                                console.log('风速控制开度更新成功!')
                                                            }).catch((err) => {
                                                                console.log(err)
                                                            })
                                                        } else {
                                                            let currentData = __retrieveData(speedArray, averageWind);//当前计算适合风速
                                                            console.log(`取到适合风速:${currentData}`)
                                                            console.log(`迎风面开度:${wardOpenArray}`)
                                                            console.log(`背风面开度:${leeOpenArray}`)

                                                            for (let j = 0; j < speedArray.length; j++) {
                                                                if (currentData === speedArray[j]) {
                                                                    console.log(`计算迎风面开度为:${wardOpenArray[j]}`)
                                                                    console.log(`计算背风面开度为:${leeOpenArray[j]}`)
                                                                    let windOpenSql = `windwardOpen=${wardOpenArray[j]},leewardOpen=${leeOpenArray[j]}`
                                                                    Mysql.UpdateParamsIntoTable('t_auto_wind', `zoneId`, env[i].zoneId, windOpenSql).then((status) => {
                                                                        console.log('风速控制开度更新成功!')
                                                                    }).catch((err) => {
                                                                        console.log(err)
                                                                    })
                                                                }
                                                            }
                                                        }
                                                    } else {
                                                        console.log('未找到合法数据，请到页面上进行设置')
                                                    }
                                                }
                                                counterAverageWind = []
                                            }


                                        } catch (err) {
                                            console.log(err)
                                        }
                                    })
                                } else {
                                    console.log('查询户外9因素传感器历史数据失败咯')
                                }
                            })

                        });

                    }

                });
            } else {
                console.log(`数据重复`)
                // lastTime = timeStamp;
            }
        } else {
            console.log(`\x1b[30;31m!!!!!!!!!下雨传感器采集故障，请及时检查！当前下雨状态：${isRain}\x1b[30;37`)
        }



    } catch (error) {
        console.log(error.message);
    }
}
export = {
    SensorDataParser,
}